<!--
 * @Description:  渠道商审核
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2022-09-02 09:21:18
 * @LastEditTime: 2023-08-03 18:20:49
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->
<template>
  <div class="lb-goods-list">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <el-button
          @click="toChange(0)"
          :type="searchForm.list.status === 0 ? 'primary' : ''"
          plain
          size="medium"
          >全部（{{ count.all || 0 }}）</el-button
        >
        <el-button
          @click="toChange(4)"
          :type="searchForm.list.status === 3 ? 'primary' : ''"
          plain
          size="medium"
          >未授权（{{ count.nopass || 0 }}）</el-button
        >
        <el-button
          @click="toChange(1)"
          :type="searchForm.list.status === 1 ? 'primary' : ''"
          plain
          size="medium"
          >申请中（{{ count.ing || 0 }}）</el-button
        >
        <el-button
          @click="toChange(2)"
          :type="searchForm.list.status === 2 ? 'primary' : ''"
          plain
          size="medium"
          >已授权（{{ count.pass || 0 }}）</el-button
        >
      </el-row>
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm.list"
          ref="listForm"
        >
          <el-form-item label="输入查询" prop="name">
            <el-input
              v-model="searchForm.list.name"
              placeholder="请输入姓名/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="申请时间" prop="start_time">
            <el-date-picker
              @change="getTableDataList(1, 'list')"
              v-model="searchForm.list.start_time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'list')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('list')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading.list"
        ref="multipleTable"
        :data="tableData.list"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
        @selection-change="handleMulSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="selectable"
          v-if="
            $route.meta.pagePermission[0].auth.includes('setChannelBalance') ||
            $route.meta.pagePermission[0].auth.includes('delChannelBalance')
          "
        ></el-table-column>
        <el-table-column prop="id" label="ID" fixed></el-table-column>
        <el-table-column prop="user_id" label="用户ID"></el-table-column>
        <el-table-column prop="avatarUrl" label="头像">
          <template slot-scope="scope">
            <lb-image :src="scope.row.avatarUrl" />
          </template>
        </el-table-column>
        <el-table-column
          prop="nickName"
          label="昵称"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="user_name"
          label="姓名"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="cate_text"
          label="申请渠道"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="admin_name"
          label="所属代理商"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="salesman_name"
          label="所属业务员"
          :min-width="120"
        ></el-table-column>
        <el-table-column prop="balance" label="提成比例" :min-width="120">
          <template slot-scope="scope" v-if="scope.row.balance !== -1">
            {{ scope.row.balance }}%
          </template>
        </el-table-column>
        <el-table-column prop="cash" label="可提现佣金" :min-width="120">
          <template slot-scope="scope"> ¥{{ scope.row.cash }} </template>
        </el-table-column>
        <el-table-column prop="total_cash" label="总佣金" :min-width="120">
          <template slot="header" slot-scope="scope">
            <div style="margin-top: 7px">
              总佣金<lb-tool-tips padding="10">包含已提现的佣金</lb-tool-tips>
            </div>
          </template>
          <template slot-scope="scope"> ¥{{ scope.row.total_cash }} </template>
        </el-table-column>
        <el-table-column prop="text" label="备注信息" min-width="200">
          <template slot-scope="scope"
            ><div
              class="ellipsis-2"
              style="max-height: 40px; line-height: 20px"
              v-html="scope.row.text"
            ></div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="申请时间" :min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="statusText[scope.row.status].type">{{
              scope.row.is_qr && scope.row.status === 2
                ? `绑定通过`
                : statusText[scope.row.status].text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="
                  scope.row.status === 2 && scope.row.is_qr
                    ? toShowDialog('edit', scope.row)
                    : toShowDialog('sub', scope.row)
                "
                v-hasPermi="
                  scope.row.status === 1
                    ? `${$route.name}-authChannel`
                    : scope.row.status === 3
                    ? `${$route.name}-resetAuth`
                    : scope.row.is_qr === 1
                    ? `${$route.name}-edit`
                    : `${$route.name}-view`
                "
                >{{
                  $t(
                    scope.row.status === 1
                      ? 'action.authChannel'
                      : scope.row.status === 3
                      ? 'action.resetAuth'
                      : scope.row.is_qr === 1
                      ? 'action.edit'
                      : 'action.view'
                  )
                }}</lb-button
              >

              <lb-button
                size="mini"
                plain
                type="danger"
                @click="
                  confirmDel(
                    {
                      id: scope.row.id
                    },
                    -1
                  )
                "
                v-show="scope.row.status !== 1"
                v-hasPermi="`${$route.name}-delete`"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="
                  confirmDel(
                    {
                      id: scope.row.id
                    },
                    3
                  )
                "
                v-show="scope.row.status === 2"
                v-hasPermi="`${$route.name}-cancelAuth`"
                >{{ $t('action.cancelAuth') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="toShowDialog('change', scope.row)"
                v-hasPermi="`${$route.name}-updateAgentSalesman`"
                v-show="scope.row.status === 2"
                >{{ $t('action.updateAgentSalesman') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="warning"
                @click="
                  toShowDialog('balance', {
                    id: [scope.row.id],
                    user_name: scope.row.user_name,
                    balance: scope.row.balance
                  })
                "
                v-hasPermi="`${$route.name}-setChannelBalance`"
                v-show="scope.row.status === 2 && !scope.row.is_qr"
                >{{ $t('action.setChannelBalance') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="
                  confirmDel(
                    {
                      id: [scope.row.id],
                      user_name: scope.row.user_name
                    },
                    -2
                  )
                "
                v-hasPermi="`${$route.name}-delChannelBalance`"
                v-show="
                  scope.row.status === 2 &&
                  scope.row.balance !== -1 &&
                  !scope.row.is_qr
                "
                >{{ $t('action.delChannelBalance') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="
          $route.meta.pagePermission[0].auth.includes('setChannelBalance') ||
          $route.meta.pagePermission[0].auth.includes('delChannelBalance')
        "
        :selected="multipleSelection.length"
        :page="searchForm.list.page"
        :pageSize="searchForm.list.limit"
        :total="total.list"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
        <lb-button
          size="mini"
          type="warning"
          @click="toBatchBalance(1)"
          v-hasPermi="`${$route.name}-setChannelBalance`"
          >{{ $t('action.setChannelBalance') }}</lb-button
        >
        <lb-button
          size="mini"
          type="danger"
          @click="toBatchBalance(2)"
          v-hasPermi="`${$route.name}-delChannelBalance`"
          >{{ $t('action.delChannelBalance') }}</lb-button
        >
      </lb-page>

      <el-dialog
        title="申请详情"
        :visible.sync="showDialog.sub"
        width="800px"
        center
      >
        <div style="height: 60vh; overflow: auto" v-if="showDialog.sub">
          <el-form
            @submit.native.prevent
            :model="applyForm"
            label-width="130px"
            size="mini"
          >
            <el-form-item label="用户ID：">
              <div>{{ applyForm.user_id }}</div>
            </el-form-item>
            <el-form-item label="昵称：">
              <div>{{ applyForm.nickName }}</div>
            </el-form-item>
            <el-form-item label="姓名：">
              <div>{{ applyForm.user_name }}</div>
            </el-form-item>
            <el-form-item label="手机号：" v-if="applyForm.mobile">
              <div>{{ applyForm.mobile }}</div>
            </el-form-item>
            <el-form-item label="申请渠道：" v-if="applyForm.cate_text">
              <div>{{ applyForm.cate_text }}</div>
            </el-form-item>
            <el-form-item label="所属代理商：" v-if="applyForm.admin_name">
              <div>{{ applyForm.admin_name }}</div>
            </el-form-item>
            <el-form-item label="所属业务员：" v-if="applyForm.salesman_name">
              <div>{{ applyForm.salesman_name }}</div>
            </el-form-item>
            <el-form-item label="备注信息：">
              <div v-html="applyForm.text"></div>
            </el-form-item>
            <el-form-item label="申请时间：">
              <div>
                {{ applyForm.create_time | handleTime() }}
              </div>
            </el-form-item>
            <div class="space-lg"></div>
            <div class="space-lg b-1px-t"></div>
            <div class="space-lg"></div>
            <block v-if="applyForm.status !== 1">
              <div class="flex-warp">
                <el-form-item
                  label="审核结果："
                  prop="status"
                  style="width: 50%"
                >
                  <el-tag :type="statusText[applyForm.status].type">{{
                    statusText[applyForm.status].text
                  }}</el-tag>
                </el-form-item>
                <el-form-item
                  label="审核时间："
                  prop=""
                  style="width: 50%"
                  v-show="applyForm.status != 1 && applyForm.sh_time"
                >
                  <div class="c-warning">
                    {{ applyForm.sh_time | handleTime() }}
                  </div>
                </el-form-item>
              </div>
              <el-form-item
                label="审核意见："
                prop="sh_text"
                v-if="applyForm.sh_text && applyForm.status !== 3"
              >
                <div>{{ applyForm.sh_text }}</div>
              </el-form-item>
            </block>
          </el-form>
          <el-form
            @submit.native.prevent
            :model="subForm"
            ref="subForm"
            :rules="subFormRules"
            label-width="130px"
            size="mini"
            v-show="[1, 3].includes(applyForm.status)"
          >
            <el-form-item label="审核结果：" prop="status" style="width: 50%">
              <el-radio-group v-model="subForm.status">
                <el-radio :label="2">通过</el-radio>
                <el-radio :label="4" v-if="applyForm.status === 1"
                  >驳回</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见：">
              <el-input
                type="textarea"
                :rows="10"
                v-model="subForm.sh_text"
                maxlength="300"
                show-word-limit
                resize="none"
                placeholder="请输入审核意见"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.sub = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('sub')"
            v-preventReClick
            v-show="[1, 3].includes(applyForm.status)"
            v-hasPermi="
              applyForm.status === 1
                ? `${$route.name}-authChannel`
                : `${$route.name}-resetAuth`
            "
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        title="编辑资料"
        :visible.sync="showDialog.edit"
        width="600px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="editForm"
          ref="editForm"
          :rules="editFormRules"
          label-width="140px"
          class="dialog-form"
        >
          <el-form-item label="渠道商姓名" prop="user_name">
            <el-input
              v-model="editForm.user_name"
              maxlength="20"
              show-word-limit
              placeholder="请输入渠道商姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="editForm.mobile"
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="申请渠道" prop="cate_id">
            <el-select
              v-model="editForm.cate_id"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in base_channel"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.edit = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('edit')"
            v-preventReClick
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('action.updateAgentSalesman')"
        :visible.sync="showDialog.change"
        width="600px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="changeForm"
          ref="changeForm"
          label-width="140px"
          class="dialog-form"
        >
          <el-form-item label="原代理商：" v-if="changeForm.admin_name">
            {{ changeForm.admin_name }}
          </el-form-item>
          <el-form-item label="原业务员：" v-if="changeForm.salesman_name">
            {{ changeForm.salesman_name }}
          </el-form-item>
          <el-form-item label="所属类型：" prop="type">
            <el-radio-group @change="toChangeType" v-model="changeForm.type">
              <el-radio :label="0" v-if="routesItem.userInfo.is_admin !== 0"
                >平台</el-radio
              >
              <el-radio :label="1">代理商</el-radio>
              <el-radio :label="2">业务员</el-radio>
            </el-radio-group>
            <lb-tool-tips>
              <div v-if="routesItem.userInfo.is_admin !== 0">
                选择平台，则该渠道商原绑定的代理商和业务员数据都将清空
              </div>
              <div class="mt-sm">
                选择代理商，则该渠道商绑定的业务员数据将清空
              </div>
              <div class="mt-sm">
                选择业务员，则该渠道商绑定的代理商也对应更改为修改后的业务员所属代理商
              </div>
            </lb-tool-tips>
            <div>
              <el-tag
                :type="changeForm.check_id ? 'primary' : 'danger'"
                @close="
                  toResetChangeForm(
                    changeForm.type === 1 ? 'admin' : 'salesman'
                  )
                "
                :closable="changeForm.check_id ? true : false"
                @click="
                  toShowDialog(changeForm.type === 1 ? 'agent' : 'salesman')
                "
                v-if="changeForm.type"
                >{{
                  changeForm.check_id
                    ? changeForm.check_name
                    : changeForm.type === 1
                    ? '选择代理商'
                    : '选择业务员'
                }}</el-tag
              >
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.change = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('change', 2)"
            v-preventReClick
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('action.setChannelBalance')"
        :visible.sync="showDialog.balance"
        width="600px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="balanceForm"
          ref="balanceForm"
          :rules="balanceFormRules"
          label-width="140px"
          class="dialog-form"
        >
          <el-form-item label="渠道商：">
            {{ balanceForm.user_name }}
          </el-form-item>
          <el-form-item label="提成比例" prop="balance">
            <el-input
              v-model="balanceForm.balance"
              placeholder="请输入提成比例"
            >
              <template slot="append">%</template>
            </el-input>
            <lb-tool-tips>提成比例取值0-100，输入0则表示没有提成</lb-tool-tips>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.balance = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('balance')"
            v-preventReClick
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        title="选择代理商"
        :visible.sync="showDialog.agent"
        width="1000px"
        center
      >
        <el-row class="page-search-form">
          <el-form
            @submit.native.prevent
            :inline="true"
            :model="searchForm.agent"
            ref="agentForm"
            class="dialog-form"
          >
            <el-form-item label="账号名称" prop="username">
              <el-input
                v-model="searchForm.agent.username"
                placeholder="请输入账号名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="关联用户" prop="nickName">
              <el-input
                v-model="searchForm.agent.nickName"
                placeholder="请输入关联用户"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <lb-button
                size="medium"
                type="primary"
                icon="el-icon-search"
                style="margin-right: 5px"
                @click="getTableDataList(1, 'agent')"
                >{{ $t('action.search') }}</lb-button
              >
              <lb-button
                size="medium"
                icon="el-icon-refresh-left"
                style="margin-right: 5px"
                @click="resetForm('agent')"
                >{{ $t('action.reset') }}</lb-button
              >
            </el-form-item>
          </el-form>
        </el-row>
        <el-table
          v-loading="loading.agent"
          :data="tableData.agent"
          ref="singleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange($event, 'agent')"
        >
          <el-table-column prop="id" label="ID" fixed></el-table-column>
          <el-table-column
            prop="username"
            label="账号名称"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="agent_name"
            label="真实姓名"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="merchant_name"
            label="商家名称"
            min-width="120"
          ></el-table-column>
          <el-table-column prop="city_type" label="代理等级" min-width="120">
            <template slot-scope="scope">
              <el-tag :type="cityType[scope.row.city_type].type">{{
                cityType[scope.row.city_type].text
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="city" label="省/城市/区县" min-width="120">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.city_type === 3
                    ? scope.row.province
                    : scope.row.city_type === 1
                    ? scope.row.city_id
                      ? `${scope.row.province} ${scope.row.city}`
                      : '-'
                    : scope.row.city_id
                    ? scope.row.province
                      ? `${scope.row.province} ${scope.row.city} ${scope.row.area}`
                      : `${scope.row.city} ${scope.row.area}`
                    : '-'
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="user_id"
            label="关联用户ID"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="nickName"
            label="关联用户昵称"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="服务电话"
            min-width="120"
          ></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.agent.page"
          :pageSize="searchForm.agent.limit"
          :total="total.agent"
          @handleSizeChange="handleSizeChange($event, 'agent')"
          @handleCurrentChange="handleCurrentChange($event, 'agent')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.agent = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm('agent')"
            v-preventReClick
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        title="选择业务员"
        :visible.sync="showDialog.salesman"
        width="1000px"
        center
      >
        <el-row class="page-search-form">
          <el-form
            @submit.native.prevent
            :inline="true"
            :model="searchForm.salesman"
            ref="salesmanForm"
            class="dialog-form"
          >
            <el-form-item label="输入查询" prop="name">
              <el-input
                v-model="searchForm.salesman.name"
                placeholder="请输入姓名/手机号"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <lb-button
                size="medium"
                type="primary"
                icon="el-icon-search"
                style="margin-right: 5px"
                @click="getTableDataList(1, 'salesman')"
                >{{ $t('action.search') }}</lb-button
              >
              <lb-button
                size="medium"
                icon="el-icon-refresh-left"
                style="margin-right: 5px"
                @click="resetForm('salesman')"
                >{{ $t('action.reset') }}</lb-button
              >
            </el-form-item>
          </el-form>
        </el-row>
        <el-table
          v-loading="loading.salesman"
          :data="tableData.salesman"
          ref="singleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange($event, 'salesman')"
        >
          <el-table-column prop="id" label="ID" fixed></el-table-column>
          <el-table-column prop="user_id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column
            prop="nickName"
            label="昵称"
            :min-width="120"
          ></el-table-column>
          <el-table-column
            prop="user_name"
            label="姓名"
            :min-width="120"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            :min-width="120"
          ></el-table-column>
          <el-table-column
            prop="admin_name"
            label="所属代理商"
            :min-width="120"
          ></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.salesman.page"
          :pageSize="searchForm.salesman.limit"
          :total="total.salesman"
          @handleSizeChange="handleSizeChange($event, 'salesman')"
          @handleCurrentChange="handleCurrentChange($event, 'salesman')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.salesman = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm('salesman')"
            v-preventReClick
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
export default {
  data () {
    let checkStatus = (rule, value, callback) => {
      if (!this.subForm.status) {
        callback(new Error('请选择审核结果'))
      } else {
        callback()
      }
    }
    return {
      selectable (row, index) {
        if (row.status === 2 && !row.is_qr) {
          return true
        } else {
          return false
        }
      },
      statusText: {
        1: {
          type: 'info',
          text: '申请中'
        },
        2: {
          type: '',
          text: '已授权'
        },
        3: {
          type: 'danger',
          text: '取消授权'
        },
        4: {
          type: 'danger',
          text: '已驳回'
        }
      },
      cityType: {
        3: {
          type: 'success',
          text: '省'
        },
        1: {
          type: 'primary',
          text: '城市'
        },
        2: {
          type: 'danger',
          text: '区县'
        }
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > (moment(moment(Date.now()).format('YYYY-MM-DD')).unix() + 24 * 3600 - 1) * 1000
        }
      },
      loading: { list: false, agent: false, salesman: false },
      searchForm: {
        list: {
          page: 1,
          limit: 10,
          status: 0,
          start_time: '',
          end_time: '',
          name: ''
        },
        agent: {
          page: 1,
          limit: 10,
          username: '',
          nickName: ''
        },
        salesman: {
          page: 1,
          limit: 10,
          status: 2,
          name: ''
        }
      },
      tableData: { list: [], agent: [], salesman: [] },
      total: { list: 0, agent: 0, salesman: 0 },
      count: {},
      showDialog: {
        sub: false,
        edit: false,
        change: false,
        agent: false,
        salesman: false,
        balance: false
      },
      multipleSelection: [],
      currentRow: {},
      applyForm: {
        title: '',
        status: '',
        sh_text: ''
      },
      subForm: {
        id: 0,
        status: 0,
        sh_text: ''
      },
      subFormRules: {
        status: { required: true, validator: checkStatus, trigger: 'blur' }
      },
      changeForm: {
        id: '',
        type: 0,
        admin_id: '',
        salesman_id: '',
        admin_name: '',
        salesman_name: '',
        check_id: '',
        check_name: ''
      },
      balanceForm: {
        id: [],
        user_name: '',
        balance: ''
      },
      balanceFormRules: {
        balance: { required: true, validator: this.$reg.isPercent, text: '提成比例', trigger: 'blur' }
      },
      editForm: {
        id: '',
        user_name: '',
        mobile: '',
        cate_id: ''
      },
      editFormRules: {
        user_name: { required: true, validator: this.$reg.isNotNull, text: '渠道商姓名', trigger: 'blur' },
        mobile: { required: true, validator: this.$reg.isTel, text: '手机号码', trigger: 'blur' }
      }
    }
  },
  async created () {
    await this.getBaseInfo()
    this.getTableDataList(1, 'list')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getBaseInfo () {
      let { data } = await this.$api.channel.cateSelect()
      this.base_channel = data
    },
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    async toChange (index) {
      this.searchForm.list.status = index
      this.getTableDataList(1, 'list')
    },
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.tableData[key] = []
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      if (key === 'list') {
        let { start_time: time } = searchForm
        if (time && time.length > 0) {
          searchForm.start_time = time[0] / 1000
          searchForm.end_time = time[1] / 1000
        } else {
          searchForm.start_time = ''
          searchForm.end_time = ''
        }
      }
      let methodArr = {
        list: { methodKey: 'channel', methodModel: 'channelList' },
        agent: { methodKey: 'agent', methodModel: 'franchiseeList' },
        salesman: { methodKey: 'salesman', methodModel: 'salesmanList' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      if (key === 'list') {
        data.data.map(item => {
          let text = item.text ? item.text : item.is_qr ? `该用户通过绑定渠道码自动成为渠道商` : `该用户没有填写备注`
          item.text = text.replace(/\n/g, '<br>')
        })
        this.count = this.$util.pick(data, ['all', 'nopass', 'ing', 'pass'])
      }
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    confirmDel (item, status) {
      let { id, user_name: name } = item
      const h = this.$createElement
      this.$confirm(h('p', null, status === -2 ? [
        h('p', null, this.$t('tips.confirmDelete')),
        h('p', { style: 'font-size:13px;line-height:1.2;color: red' }, `删除后，渠道商“${name}”的提成比例将默认为【渠道商设置 - 渠道商返佣】所设置的比例`)
      ] : [
        h('p', null, this.$t(status === 3 ? 'tips.confirmNoPass' : 'tips.confirmDelete'))
      ]), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id, status, 'list')
      }).catch(() => {

      })
    },
    async updateItem (id, status, key) {
      let methodModel = status === -2 ? 'delChannelBalance' : 'channelUpdate'
      this.$api.channel[methodModel](status === -2 ? { id } : { id, status }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === 3 ? 'tips.successOper' : 'tips.successDel'))
          if (status === -1) {
            this.searchForm[key].page = this.searchForm[key].page < Math.ceil((this.total[key] - 1) / this.searchForm[key].limit) ? this.searchForm[key].page : Math.ceil((this.total[key] - 1) / this.searchForm[key].limit)
          }
          this.getTableDataList('', key)
        } else {
          if (status === -1) return
          this.getTableDataList('', key)
        }
      })
    },
    async toShowDialog (key, item = {}) {
      item = JSON.parse(JSON.stringify(item))
      if (['change', 'balance', 'edit'].includes(key)) {
        if (key === 'change') {
          let arr = ['admin', 'salesman']
          arr.map(i => {
            item[`${i}_id`] = item[`${i}_id`] && item[`${i}_name`] ? item[`${i}_id`] : ''
          })
          let { admin_id: aid, salesman_id: sid, admin_name: aname, salesman_name: sname } = item
          let type = sid && sname ? 2 : aid && aname ? 1 : 0
          item.type = type
          let id = type === 2 ? sid : type === 1 ? aid : ''
          let uname = type === 2 ? sname : type === 1 ? aname : ''
          item.check_id = id
          item.check_name = uname
        }
        if (key === 'balance') {
          item.balance = item.balance === -1 ? '' : item.balance
        }
        if (key === 'edit') {
          item.cate_id = item.cate_id || ''
        }
        for (let i in this[`${key}Form`]) {
          this[`${key}Form`][i] = item[i]
        }
      } else if (key === 'sub') {
        let { id } = item
        let { code, data } = await this.$api.channel.channelInfo({ id })
        if (code !== 200) return
        let text = data.text ? data.text : data.is_qr ? `该用户通过绑定渠道码自动成为渠道商` : `该用户没有填写备注`
        data.text = text.replace(/\n/g, '<br>')
        this.applyForm = data
        this.subForm = {
          id,
          status: 2,
          sh_text: ''
        }
      } else {
        this.currentRow = {}
        if (key === 'salesman') {
          this.searchForm[key].name = ''
        } else {
          this.searchForm[key].username = ''
          this.searchForm[key].nickName = ''
        }
        await this.getTableDataList(1, key)
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    toChangeType () {
      this.changeForm.admin_id = 0
      this.changeForm.salesman_id = 0
      this.changeForm.check_id = 0
      this.changeForm.check_name = ''
      this.currentRow = {}
    },
    toResetChangeForm (key) {
      this.changeForm[`${key}_id`] = 0
      this.changeForm.check_id = 0
      this.changeForm.check_name = ''
      this.currentRow = {}
    },
    handleMulSelectionChange (val) {
      this.multipleSelection = val
    },
    handleSelectionChange (val = {}, key) {
      val = JSON.parse(JSON.stringify(val))
      if (key === 'agent') {
        val.user_name = val.agent_name
      }
      this.currentRow = val
    },
    handleDialogConfirm (key) {
      if (this.currentRow === null || !this.currentRow.id) {
        this.$message.error(key === 'agent' ? `请选择代理商` : `请选择业务员`)
        return
      }
      let { id = 0, admin_id: aid, user_name: uname } = this.currentRow
      if (key === 'salesman') {
        this.changeForm.salesman_id = id
        this.changeForm.admin_id = aid
      } else {
        this.changeForm.admin_id = id
      }
      this.changeForm.check_id = id
      this.changeForm.check_name = uname
      this.showDialog[key] = false
    },
    toBatchBalance (key) {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择要操作的数据`)
        return
      }
      let arr = this.multipleSelection.filter(item => {
        return key === 1 ? item.id : item.id && item.balance !== -1
      })
      let id = arr.map(item => {
        return item.id
      })
      if (id.length === 0) {
        this.$message.error(`当前选择的数据暂未设置提成比例，不可操作删除提成比例哦`)
        return
      }
      let name = ''
      arr.map((item, index) => {
        name += `${index === 0 ? '' : '、'}${item.user_name}`
      })
      if (key === 1) {
        this.balanceForm = {
          id,
          user_name: name,
          balance: ''
        }
        this.showDialog.balance = true
        return
      }
      this.confirmDel({ id, user_name: name }, -2)
    },
    async submitFormInfo (key, validate = 1) {
      let flag = true
      if (validate === 1) {
        this.$refs[`${key}Form`].validate(valid => {
          if (!valid) flag = false
        })
      }
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
        if (key === 'change') {
          let { type, admin_id: aid, salesman_id: sid } = subForm
          if ((type === 1 && !aid) || (type === 2 && !sid)) {
            this.$message.error(type === 1 ? `请选择代理商` : `请选择业务员`)
            return
          }
          if (subForm.type === 0) {
            subForm.admin_id = 0
          }
          delete subForm.type
          delete subForm.admin_name
          delete subForm.salesman_name
          delete subForm.check_id
          delete subForm.check_name
        }
        if (key === 'balance') {
          delete subForm.user_name
        }
        let methodModel = key === 'balance' ? 'setChannelBalance' : 'channelUpdate'
        this.$api.channel[methodModel](subForm).then((res) => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successSub'))
            this.showDialog[key] = false
            this.getTableDataList('', 'list')
          }
        })
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  .el-input {
    width: 200px;
  }
  .el-image {
    width: 120px;
    height: 120px;
  }
  .el-textarea {
    width: 600px;
  }
}
.dialog-form {
  .el-input,
  .el-select {
    width: 300px;
  }
}
</style>
